package com.jinandi.app.util.security;

import java.util.Collection;
import java.util.Iterator;

import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

@SuppressWarnings("rawtypes")
public class AuditPointVoter implements AccessDecisionVoter {

	@Override
	public boolean supports(ConfigAttribute arg0) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean supports(Class arg0) {
		// TODO Auto-generated method stub
		return true;
	}
	/**
	 * @param authentication
	 *            用户拥有的权限
	 * @param object
	 *            用户访问的请求
	 * @param collection
	 *            当前请求所需要的权限
	 */
	@Override
	public int vote(Authentication authentication, Object object,
			Collection collection) {
		int result = ACCESS_ABSTAIN;
		Iterator iter = collection.iterator();
		while (iter.hasNext()) {
			ConfigAttribute attribute = (ConfigAttribute) iter.next();

			if (this.supports(attribute)) {
				result = ACCESS_DENIED;
				if (attribute.getAttribute().equals("/")) {
					return ACCESS_GRANTED;
				}
				Iterator<? extends GrantedAuthority> iterator = authentication
						.getAuthorities().iterator();
				while (iterator.hasNext()) {
					String authority = iterator.next().getAuthority();
					if (attribute.getAttribute().equals(authority)) {
						return ACCESS_GRANTED;
					}
				}
			}
		}
		return result;
	}

}
